﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Common.Core.Configuration
{
	public class ConfigurationContainer<InstanceType> : ConfigurationContainer where InstanceType : ConfigurationContainer<InstanceType>, new()
	{
		public static InstanceType Instance
		{
			get { return instance; }
		}	readonly static InstanceType instance = new InstanceType();
	}

	public class ConfigurationContainer : ResourceDictionary
	{
		public string DefaultKeyName { get; set; }

		public ItemType Get<ItemType>()
		{
			var keys = from key in Keys.Cast<string>()
			            where key == DefaultKeyName
			            select (ItemType)this[key];

			var all = GetAll<ItemType>();
			var set = keys.Concat( all );

			var result = set.FirstOrDefault();
			return result;
		}

		public IEnumerable<ItemType> GetAll<ItemType>()
		{
			var result = from key in Keys.Cast<string>()
						 let creator = this[key] as IObjectCreator<ItemType>
						 let item = creator == null && !Equals( this[ key ], default( ItemType ) ) && typeof(ItemType).IsAssignableFrom( this[ key ].GetType() ) ? (ItemType)this[key] : default(ItemType)
						 select creator != null ? creator.Create() : item;
			return result;
		}

		public ItemType Get<ItemType>( string name )
		{
			var item = Contains( name ) ? this[ name ] : default( ItemType );
			var result = (ItemType)item;
			return result;
		}
	}
}
